from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from instafeed.conduits.models import Conduit, get_conduit_plugins, get_conduit_plugin
from instafeed.conduits.forms import ConduitForm
from django.http import HttpResponseRedirect

# Create your views here.
@login_required
def manage_conduits(request):
    conduits = Conduit.objects.filter(user=request.user)
    return render_to_response("manage_conduits.html",
        {'conduits': conduits},
        context_instance=RequestContext(request))

@login_required
def new_conduit(request):
    template_params = {}
    template_params["next"] = request.GET.get("next", request.POST.get("next", "/"))
    template_params["plugin"] = request.GET.get("plugin", None)

    if request.method == "POST":
        form = ConduitForm(request.POST)
        if form.is_valid():
            plugin_key = form.cleaned_data["plugin"]
            plugin = get_conduit_plugin(plugin_key)
            is_valid, params = plugin.validate_new(request)
            if is_valid:
                new_conduit = form.save(commit=False)
                new_conduit.user = request.user
                new_conduit.params = repr(params)
                new_conduit.save()
                return HttpResponseRedirect(template_params["next"])
            else:
                template_params.update(params) # If isn't valid params returns template_params,
                                               # for example a form with the errors
        template_params["form"] = form
    elif template_params["plugin"]:
        template_params["form"] = ConduitForm(initial={'plugin': template_params["plugin"]})
    else:
        template_params["form"] = ConduitForm()
    plugins = [p for p in get_conduit_plugins() if p.allowNew]
    template_params["conduit_plugins"] = plugins
    for p in plugins:
        p.update_template_params(request, template_params)

    return render_to_response("new_conduit.html", template_params,
        context_instance=RequestContext(request))

@login_required
def delete_conduit(request, conduitId):
    conduit = get_object_or_404(Conduit, pk=conduitId)
    if conduit.user == request.user:
        conduit.delete()
    return HttpResponseRedirect("/manage_conduits")
